package com.jit.BluetoothKey.activity;


import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelUuid;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.jit.BluetoothKey.R;
import com.jit.BluetoothKey.activity.base.BaseActivity;
import com.jit.BluetoothKey.entity.InstructionsBean;
import com.jit.BluetoothKey.fragment.ControlFragment;
import com.jit.BluetoothKey.fragment.ParkFragment;
import com.jit.BluetoothKey.fragment.SettingFragment;
import com.jit.BluetoothKey.fragment.StateFragment;
import com.jit.BluetoothKey.service.HelloteacherService;
import com.jit.BluetoothKey.utils.BleControllerUtil;
import com.jit.BluetoothKey.utils.ByteUtil;
import com.jit.BluetoothKey.utils.CarStatusResponseHelper;
import com.jit.BluetoothKey.utils.ControlInstruction;
import com.jit.BluetoothKey.utils.HexStr2BinUtil;
import com.jit.BluetoothKey.utils.SharedPreferencesUtil;
import com.jit.BluetoothKey.utils.ToastUtils;
import com.jit.BluetoothKey.utils.UserFiled;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    private RadioGroup radioGroup;
    private FragmentManager FragmentManager;
    private Fragment nowFragment;
    private List<BluetoothDevice> bluetoothDevices = new ArrayList<>();
    private long lastTime; // 记录上次点击返回时间点
    private ImageView userImg;
    private BleDevice targertBleDevice;  //扫描的目标蓝牙设备
    private boolean isConnection = false;
    private boolean isFind = false;
    private BluetoothGattCharacteristic writeCharacters;
    private ImageView statusIv;
    private int carStatusRequestTag = 0;  //标识当前响应的是哪一个状态请求
    private boolean hadResponse = false; //标识用户的状态请求是否响应
    private boolean hadLogin = false; // 标识用户是否已经在蓝牙处登录
    private boolean isStatusPage = true;  //标识当前是否是状态页面，做请求状态与否判断
    private final String BROADCAST_PERMISSION_DISC = "com.jit.bluetooth.permissions.MY_BROADCAST";

    private BroadcastReceiver mStatusReceive = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case BluetoothAdapter.ACTION_STATE_CHANGED:
                    int blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
                    switch (blueState) {
                        case BluetoothAdapter.STATE_TURNING_ON:
                            break;
                        case BluetoothAdapter.STATE_ON:    //监听蓝牙状态 蓝牙由关闭到开启 再次扫描连接
                            bleScanAndConnection(SharedPreferencesUtil.getString(MainActivity.this, UserFiled.BINGDING_BLUETOOTH));
//                            开始扫描
                            break;
                        case BluetoothAdapter.STATE_TURNING_OFF:
                            break;
                        case BluetoothAdapter.STATE_OFF:
                            break;
                    }
                    break;
            }
        }
    };

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    bleScanAndConnection(SharedPreferencesUtil.getString(MainActivity.this, UserFiled.BINGDING_BLUETOOTH));
                    break;
                case 2:
                    handler.removeMessages(3);
                    carStatusRequest();
                    break;
                case 3:
                    handler.removeMessages(2);
                    if (!hadResponse) {
                        if (carStatusRequestTag < 4) { //如果carStatusRequestTag 小于4 表示一次状态请求没有完成
                            carStatusRequestTag++;
                            handler.sendEmptyMessage(2);
                        } else if (carStatusRequestTag == 4) {  //如果carStatusRequestTag 等于4 表示一次状态请求完成延迟做下一次请求 carStatusRequestTag 置为0
                            carStatusRequestTag = 0;
                            handler.sendEmptyMessage(2);
                        }
                    }
                    break;
            }
            return true;
        }
    });
    private Intent service;
    private BluetoothGattCharacteristic indictionCharacteristic;
    private TextView name;
    private BluetoothLeAdvertiser mBTAdvertiser;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        inProcess();  //开启前台服务
        radioGroup.check(R.id.main_status_radiobutton);
        bleScanAndConnection(SharedPreferencesUtil.getString(this, UserFiled.BINGDING_BLUETOOTH));

        // TODO: 2018/3/9 用于测试开启应用开启ibecon 广播   5AA502010000后面补0
//        createIbeacon("5AA502010000000000000000000000000000F5FA");

    }


    @Override
    protected void onResume() {
        super.onResume();
        /**
         *  注册蓝牙开关开启关闭监听
         */
        IntentFilter statusFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mStatusReceive, statusFilter,BROADCAST_PERMISSION_DISC,null);
    }

    /**
     *   创建Ibeacon 广播
     * @param data  接受到的来自中心设备的报文
     */
    private void createIbeacon(String data) {
        String substring = data.substring(6, data.length());  //截取数据场数据
        String binStr = HexStr2BinUtil.bytes2BinStr(HexUtil.hexStringToBytes(substring)); //16进制数据转换为2进制数据
        int mode = Integer.valueOf(binStr.substring(0,8),2);  //关闭 或开启模式
        int powerLevel = Integer.valueOf(binStr.substring(8,16),2);
        int time = Integer.valueOf(binStr.substring(16,32),2);
        BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (manager != null) {
            BluetoothAdapter mBTAdapter = manager.getAdapter();
            if (mode!=0) {  //不为0 开启Ibeacon 广播
                startAdvertise(mBTAdapter,mode,powerLevel,time);
            }else {
                stopAdvertise();  //为0 关闭Ibeacon广播
            }
        }

    }


    /**
     *   开启Ibeacon 广播
     * @param mBTAdapter
     * @param mode  开始Ibeacon 的广播模式
     * @param powerLevel 开启Ibeacon的能耗等级
     * @param time Ibeacon 的持续时间
     */
    private void startAdvertise(BluetoothAdapter mBTAdapter,int mode,int powerLevel,int time) {
        if (mBTAdapter == null) {
            return;
        }
        if (mBTAdvertiser == null) {
            mBTAdvertiser = mBTAdapter.getBluetoothLeAdvertiser();
        }


        //ibeacon 配置代码
//=========================================================================================================
        mBTAdapter.setName("AZX");   //录入广播name  暂时未起作用
        mBTAdapter.startDiscovery();
        if (mBTAdvertiser != null) {
            mBTAdvertiser.startAdvertising(
                    createAdvertiseSettings(mode,powerLevel,time),
                    createAdvertiseData(UUID.fromString("fda50693-a4e2-4fb1-afcf-c6eb07647825"), // 当前为微信UUID，待后续录入自定义UUID 格式按照fda50693-a4e2-4fb1-afcf-c6eb07647825
                            10, 5, (byte) 0x4c00,100),   //  10 为major 5 为minor  都为标识字段 ， 0x4c00  厂商id 用于表示App的厂商，  100 测量功率不是发射功率 当前未起作用
                    mAdvCallback);
        }
//==============================================================================================================
    }

    /**
     *   关闭广播调用
     *
     */
    private void stopAdvertise(){
        if (mBTAdvertiser!=null){
            mBTAdvertiser.stopAdvertising(stopCallBack);
        }
    }

    /**
     *   关闭广播回调
     */
    private AdvertiseCallback stopCallBack = new AdvertiseCallback() {
        @Override
        public void onStartSuccess(AdvertiseSettings settingsInEffect) {
            super.onStartSuccess(settingsInEffect);
            Log.d("debug", "stopSuccess");
        }

        @Override
        public void onStartFailure(int errorCode) {
            super.onStartFailure(errorCode);
            Log.d("debug", "stopError");
        }
    };

    /**
     *   ibeacon 开启监听回调
     */
    private AdvertiseCallback mAdvCallback = new AdvertiseCallback() {
        public void onStartSuccess(android.bluetooth.le.AdvertiseSettings settingsInEffect) {

            // TODO: 2018/3/16  响应Ibeacon
            try {
                bleDataWrite(targertBleDevice,
                        writeCharacters.getService().getUuid().toString(),
                        writeCharacters.getUuid().toString(),
                        HexUtil.hexStringToBytes(ControlInstruction.IBEACON_SUCCESS));
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (settingsInEffect != null) {
                Log.d("debug", "onStartSuccess TxPowerLv="
                        + settingsInEffect.getTxPowerLevel()
                        + " mode=" + settingsInEffect.getMode()
                        + " timeout=" + settingsInEffect.getTimeout());
            } else {
                Log.d("debug", "onStartSuccess, settingInEffect is null");
            }
//            switchView.setChecked(true);
            setProgressBarIndeterminateVisibility(false);
        }

        public void onStartFailure(int errorCode) {
            Log.d("debug", "onStartFailure errorCode=" + errorCode);
//            switchView.setChecked(false);
            try {
                bleDataWrite(targertBleDevice,
                        writeCharacters.getService().getUuid().toString(),
                        writeCharacters.getUuid().toString(),
                        HexUtil.hexStringToBytes(ControlInstruction.IBEACON_ERROR));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };


    /**
     *   Ibeacon 广播设置
     * @param
     * @param timeoutMillis  超时时间
     * @return
     */
    public AdvertiseSettings createAdvertiseSettings(int mode,int powerLevel, int timeoutMillis) {
        AdvertiseSettings.Builder builder = new AdvertiseSettings.Builder();
        builder.setConnectable(true);   //设置连接方式 不可连接
        switch (mode){//设置广播模式
            case 1:
                builder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_POWER);
                break;
            case 2:
                builder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED);
                break;
            case 3:
                builder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY);
                break;
        }
        switch (powerLevel){
            case 0:
                builder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_ULTRA_LOW);
                break;
            case 1:
                builder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_LOW);
                break;
            case 2:
                builder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM);
                break;
            case 3:
                builder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH);
                break;
        }
        builder.setTimeout(timeoutMillis);  //设置广播开启时间

        return builder.build();
    }

    /**
     *   创建Ibeacon 广播报文
     * @param proximityUuid  设备UUID
     * @param major  主标识
     * @param minor  副标识
     * @param id 厂商id
     * @param txPower 测量功率
     * @return
     */
    public AdvertiseData createAdvertiseData(UUID proximityUuid, int major,
                                             int minor, byte id,int txPower) {
        if (proximityUuid == null) {
            throw new IllegalArgumentException("proximitiUuid null");
        }
        byte[] manufacturerData = new byte[23];
        ByteBuffer bb = ByteBuffer.wrap(manufacturerData);
        bb.order(ByteOrder.BIG_ENDIAN);
        bb.put((byte) 0x02);
        bb.put((byte) 0x15);
        bb.putLong(proximityUuid.getMostSignificantBits());
        bb.putLong(proximityUuid.getLeastSignificantBits());
        bb.putShort((short) major);
        bb.putShort((short) minor);
        bb.put((byte) txPower);

        AdvertiseData.Builder builder = new AdvertiseData.Builder();
        builder.addManufacturerData(id, manufacturerData);
        AdvertiseData adv = builder.build();
        return adv;
    }

    //进程函数
    private void inProcess() {
        service = new Intent(this, HelloteacherService.class);
        startService(service);
    }

    /**
     * 蓝牙扫描连接服务
     */

    private void bleScanAndConnection(String macAddress) {
        if (!macAddress.equals("") && SharedPreferencesUtil.getIsLogin(this, UserFiled.BLE_AUTO_CONNECTION)) {  // 表示已经绑定了蓝牙并且开启自动扫描才进行搜索
            bleScan(macAddress);
        }
    }

    /**
     * 蓝牙扫描
     */
    private void bleScan(final String macAddress) {
        /**
         *  扫描的监听回调
         */
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                if (success) {

                }
            }

            @Override
            public void onScanning(BleDevice result) {
                if (result.getMac().equals(macAddress)) { //筛选扫描到蓝牙
                    BleManager.getInstance().cancelScan();
                    //连接开始时 断开所有连接
                    BleManager.getInstance().disconnectAllDevice();
                    isFind = true;
                    targertBleDevice = result;
                    //扫描到目标蓝牙设备进行连接
                    bleConnection(targertBleDevice);
                    //扫描到目标蓝牙设备停止扫描
//                    }
                }
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                Log.i("tag", "onScanFinished: ==============>" + scanResultList.size());
                if (!isFind) {
                    bleScanAndConnection(SharedPreferencesUtil.getString(MainActivity.this, UserFiled.BINGDING_BLUETOOTH));
                }
            }
        });
    }


    /**
     * 控制指令发送
     *
     * @param instructionsBean
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void sendInstructions(InstructionsBean instructionsBean) {
        if (isConnection && targertBleDevice!=null) {
            // TODO: 2018/2/26   发送指令
            byte[] bytes = HexUtil.hexStringToBytes(instructionsBean.getInstruction());
            bleDataWrite(targertBleDevice,
                    writeCharacters.getService().getUuid().toString(),
                    writeCharacters.getUuid().toString(),
                    bytes);
        } else {
            ToastUtils.showToast(this, "当前蓝牙未连接");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void bleBindScan(String evnet) {
        if (evnet.equals(UserFiled.BLE_CHANGE)) {
            BleManager.getInstance().disconnectAllDevice();
            isConnection = false;
            isFind = false;
            bleScanAndConnection(SharedPreferencesUtil.getString(this, UserFiled.BINGDING_BLUETOOTH));
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mStatusReceive);
    }

    @Override
    protected void onDestroy() {
        Log.e("tag", "onDestroy: ");
        isConnection = false;
        targertBleDevice = null;
        stopService(service);  //关闭服务
        BleManager.getInstance().cancelScan();
        BleManager.getInstance().destroy();
        BleManager.getInstance().disconnectAllDevice();
        BleManager.getInstance().destroy();
        if (targertBleDevice != null) {
            BleManager.getInstance().disconnect(targertBleDevice);
        }
        //// TODO: 2018/2/24   移除监听
        EventBus.getDefault().unregister(this);  // 注销eventbus
        stopAdvertise();
        super.onDestroy();
    }

    /**
     * 设备连接方法
     *
     * @param bleDevice
     */
    private void bleConnection(final BleDevice bleDevice) {
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                //开始连接
            }

            @Override
            public void onConnectFail(BleException exception) {
                //连接失败
                bleConnection(targertBleDevice);
            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                // 连接成功，筛选所对应的服务列表
                bleConnectionStatus();
                ToastUtils.showToast(MainActivity.this, "蓝牙连接成功");
                serviceFiltrate(bleDevice);

            }

            /**
             *
             * @param isActiveDisConnected  是否为主动断开
             * @param device
             * @param gatt
             * @param status
             */
            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                bleDisconnectionStatus(); //蓝牙断开连接改变界面图标
                isFind = false;
                isConnection = false;  // 断开连接将连接状态置为false；

                BleManager.getInstance().disconnectAllDevice(); //断开连接断开所有蓝牙连接
                // TODO: 2018/2/23  蓝牙连接断开时回调
                ToastUtils.showToast(MainActivity.this, "蓝牙断开连接");
                BleManager.getInstance().disconnect(targertBleDevice);
                targertBleDevice = null;
                // TODO: 2018/2/23  断开连接 重新扫描延时扫描
                handler.sendEmptyMessageDelayed(1,2000);
                // TODO: 2018/3/27  断开连接关闭ibeacon 广播
                stopAdvertise();
            }
        });
    }

    /**
     * 筛选服务列表
     *
     * @param bleDevice
     */
    private void serviceFiltrate(BleDevice bleDevice) {
        BluetoothGatt bluetoothGatt = BleManager.getInstance().getBluetoothGatt(bleDevice);
        for (BluetoothGattService server : bluetoothGatt.getServices()) {
            if (!server.getUuid().toString().equals(UserFiled.DEFUALT_SERVICE1_UUID) && !server.getUuid().toString().equals(UserFiled.DEFUALT_SERVICE2_UUID)) {
                Logger.d(server.getUuid());
                characteristic(server);
            }
        }
    }

    /**
     * 特征筛选
     *
     * @param server
     */
    private void characteristic(BluetoothGattService server) {
        for (BluetoothGattCharacteristic characteristic : server.getCharacteristics()) {
            int charaProp = characteristic.getProperties(); // 特征标识
            if ((charaProp & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                indictionCharacteristic = characteristic;
                // TODO: 2018/2/23   为读特性时开启监听
                BleManager.getInstance().notify(
                        targertBleDevice,
                        characteristic.getService().getUuid().toString(),
                        characteristic.getUuid().toString(),
                        new BleNotifyCallback() {

                            @Override
                            public void onNotifySuccess() {

                            }

                            @Override
                            public void onNotifyFailure(final BleException exception) {

                            }

                            @Override
                            public void onCharacteristicChanged(byte[] data) {
                                // TODO: 2018/3/7   分辨不同返回报文做响应
                                String responseData = HexUtil.formatHexString(data);
                                Log.i("tag", "onCharacteristicChanged: ============>" + responseData);
                                String responseType = responseData.substring(4, 6);
                                switch (responseType) {
                                    case "02":  //Ibeancon广播响应
                                        createIbeacon(responseData);
                                        break;
                                    case "01":   //认证请求
                                        authenticationResponse(data);
                                        break;
                                    case "71":  //车辆状态信息
                                        if (carStatusRequestTag < 4) { //如果carStatusRequestTag 小于4 表示一次状态请求没有完成
                                            carStatusRequestTag++;
                                            handler.sendEmptyMessage(2);
                                            hadResponse = true;
                                        } else if (carStatusRequestTag == 4) {  //如果carStatusRequestTag 等于4 表示一次状态请求完成延迟做下一次请求 carStatusRequestTag 置为0
                                            carStatusRequestTag = 0;
                                            handler.sendEmptyMessageDelayed(2, 3000);
                                            hadResponse = true;
                                        }
                                        carStatusResove(data);
                                        break;
                                    case "60":  // 登录成功应答
                                        hadLogin = true;
                                        break;
                                }
                            }
                        });
            }
            if ((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) > 0) {
                writeCharacters = characteristic;
                isConnection = true;  // 连接成功将连接状态置为true
                // TODO: 2018/3/7   写状态读取后 车辆状态请求广播
                handler.sendEmptyMessageDelayed(2, 3000);
            }

        }
    }


    private void carStatusResove(byte[] data) {
        String s1 = HexUtil.formatHexString(data);
        String usefulData = s1.substring(6, s1.length()); // 数据场数据 从第四个字节开始
        CarStatusResponseHelper.carStatusAnalysis(usefulData);
    }

    private void carStatusRequest() {
        if (isConnection && isFind && isStatusPage) {
            // TODO: 2018/2/26   发送指令
            String requestString = "";
            switch (carStatusRequestTag) {
                case 0:
                    requestString = ControlInstruction.CAR_STATUS_RESPONSE;
                    break;
                case 1:
                    requestString = ControlInstruction.CAR_TIRE_PRESSURE1;
                    break;
                case 2:
                    requestString = ControlInstruction.CAR_TIRE_PRESSURE2;
                    break;
                case 3:
                    requestString = ControlInstruction.CAR_TIRE_PRESSURE3;
                    break;
                case 4:
                    requestString = ControlInstruction.CAR_TIRE_PRESSURE4;
                    break;
            }
            byte[] bytes = HexUtil.hexStringToBytes(requestString);
            carStatusWrite(targertBleDevice,
                    writeCharacters.getService().getUuid().toString(),
                    writeCharacters.getUuid().toString(),
                    bytes);
            hadResponse = false;
        }
    }

    private void carStatusWrite(BleDevice targertBleDevice, String serviceUUID, String characterUUID, byte[] data) {

        if (isConnection&&targertBleDevice!=null) {
            BleManager.getInstance().write(targertBleDevice, serviceUUID, characterUUID, data, new BleWriteCallback() {
                @Override
                public void onWriteSuccess(int current, int total, byte[] justWrite) {
                    if (carStatusRequestTag != 4) {
                        handler.sendEmptyMessageDelayed(3, 100);
                    } else {
                        handler.sendEmptyMessageDelayed(3, 3100);
                    }
                }

                @Override
                public void onWriteFailure(BleException exception) {
                    carStatusRequest(); // 发送失败继续调用发送方法
                }
            });
        }
    }


    /**
     * 认证请求响应
     *
     * @param data 响应数据
     */
    private void authenticationResponse(byte[] data) {
        try {
            String respondsSub = BleControllerUtil.respondsSub(SharedPreferencesUtil.getString(MainActivity.this, UserFiled.SK), data);
            byte[] bytes = HexUtil.hexStringToBytes(respondsSub);
            bleDataWrite(targertBleDevice,
                    writeCharacters.getService().getUuid().toString(),
                    writeCharacters.getUuid().toString(),
                    bytes);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("tag", "加密失败明码长度错误");
        }

        // TODO: 2018/3/9  认证结束发送用户识别到中心蓝牙设备

        if (!hadLogin) {
            String account = SharedPreferencesUtil.getString(this, UserFiled.ACCOUNT);
            String s = account + String.format("%1$0" + (14 - account.length()) + "d", 0);
            byte[] bytes1 = ByteUtil.byteMerger(HexUtil.hexStringToBytes(ControlInstruction.USER_HEAD), s.getBytes());
            byte[] bytesData = ByteUtil.byteMerger(bytes1, HexUtil.hexStringToBytes(ControlInstruction.PACKGE_FOOT));
            bleDataWrite(targertBleDevice,
                    writeCharacters.getService().getUuid().toString(),
                    writeCharacters.getUuid().toString(),
                    bytesData);
        }

    }

    /**
     * @param targertBleDevice 进行通信的目标蓝牙设备
     * @param serviceUUID      对应服务的UUID
     * @param characterUUID    写特征的UUID
     * @param data             传输数据
     */

    private void bleDataWrite(BleDevice targertBleDevice, String serviceUUID, String characterUUID, byte[] data) {

        if (isConnection&&targertBleDevice!=null) {
            BleManager.getInstance().write(targertBleDevice, serviceUUID, characterUUID, data, new BleWriteCallback() {
                @Override
                public void onWriteSuccess(int current, int total, byte[] justWrite) {
    //                ToastUtils.showToast(MainActivity.this, "控制指令发送成功");
                }

                @Override
                public void onWriteFailure(BleException exception) {

                }
            });
        }
    }

    /**
     * 蓝牙连接状态改变
     */
    private void bleConnectionStatus() {
        if (statusIv != null) {
            statusIv.setImageResource(R.mipmap.main_car_connect);
        }
    }

    /**
     * 蓝牙断开连接状态改变
     */
    private void bleDisconnectionStatus() {
        if (statusIv != null) {
            statusIv.setImageResource(R.mipmap.main_car_disconnect);
        }
    }

    @Override
    protected void initAdapt() {
        super.initAdapt();
    }


    @Override
    protected void initView() {
        super.initView();
        radioGroup = (RadioGroup) findViewById(R.id.main_radiogroup);
        FragmentManager = getSupportFragmentManager();
        userImg = (ImageView) findViewById(R.id.main_user_img);
        statusIv = (ImageView) findViewById(R.id.main_connection_status_iv);
        name = (TextView) findViewById(R.id.main_user_name);
    }

    @Override
    protected void initData() {
        super.initData();
        name.setText(SharedPreferencesUtil.getString(this, UserFiled.ACCOUNT));
    }

    @Override
    protected void initListner() {
        super.initListner();
        radioGroup.setOnCheckedChangeListener(this);
        userImg.setOnClickListener(this);
    }

    /**
     * @param group
     * @param checkedId radioGroup 接口回调
     */
    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        FragmentChange(checkedId);
        switch (checkedId) {
            case R.id.main_status_radiobutton:
                isStatusPage = true;
                carStatusRequest();  //切换到状态页面 开启请求
                break;
            case R.id.main_controll_radiobutton:
                isStatusPage = false;
                break;
            case R.id.mian_park_radiobutton:
                isStatusPage = false;
                break;
            case R.id.main_setting_radiobutton:
                isStatusPage = false;
                break;
        }
    }

    /**
     * 接口回调 切换逻辑
     *
     * @param checkedId
     */
    private void FragmentChange(int checkedId) {
        Fragment fragment = null;
        if (FragmentManager.findFragmentById(checkedId) == null) {
            switch (checkedId) {
                case R.id.main_status_radiobutton:
                    fragment = new StateFragment();
                    break;
                case R.id.main_controll_radiobutton:
                    fragment = new ControlFragment();
                    break;
                case R.id.mian_park_radiobutton:
                    fragment = new ParkFragment();
                    break;
                case R.id.main_setting_radiobutton:
                    fragment = new SettingFragment();
                    break;
            }
            FragmentTransaction fragmentTransaction = FragmentManager.beginTransaction();
            fragmentTransaction.add(R.id.main_framlayout, fragment, String.valueOf(checkedId));
            if (nowFragment != null) {
                fragmentTransaction.hide(nowFragment);
            }
            fragmentTransaction.commit();
            nowFragment = fragment;
        } else {
            FragmentTransaction fragmentTransaction = FragmentManager.beginTransaction();
            if (nowFragment != null) {
                fragmentTransaction.hide(nowFragment);
            }
            fragmentTransaction.show(FragmentManager.findFragmentByTag(String.valueOf(checkedId)));
            fragmentTransaction.commit();
            nowFragment = FragmentManager.findFragmentByTag(String.valueOf(checkedId));
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_user_img:
                startActivity(new Intent(this, AccountActivity.class));
                break;
        }
    }

    //双击退出逻辑
    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - lastTime > 1000) {
            ToastUtils.showToast(this, "双击退出");
            lastTime = System.currentTimeMillis();
        } else {
            super.onBackPressed();
        }
    }
}
